package com.lovo.psc.controller;

import com.alibaba.fastjson.JSON;
import com.lovo.psc.bean.OrderBean;
import com.lovo.psc.service.IOrderService;
import com.lovo.psc.vo.OrderVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("order")
public class OrderController {


    @Autowired
    private IOrderService service;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("findAll")
    public List<OrderBean> findAll(){
        List<OrderBean> lst = service.findAll();
        return getOrderBeans(lst);

    }

    @GetMapping("findByOrderId/{id}")
    public List<OrderVo> findByOrderId(@PathVariable("id") int id){
        List<OrderVo> lst = service.findByOrderId(id);
        for (OrderVo o:lst){
            if (o.getStatus() ==0){
                o.setNewStatus("已供货");
            }else if(o.getStatus()==1){
                o.setNewStatus("已入库");
            }else {
                o.setNewStatus("已退货");
            }
        }
        return lst;
    }

    @GetMapping("updateById/{id}/{status}")
    public String updateById(@PathVariable("id") long id,@PathVariable("status") int status){
        service.updateById(id,status);
        //发送到MQ
        if (status ==1) {
            OrderBean orderBean = service.findById(id);
            String json = JSON.toJSONString(orderBean);
            rabbitTemplate.convertAndSend("directExchangeOrder", "replenishOrder.key", json);
            System.out.println("发送成功");
        }
        return "ok";
    }

    @GetMapping("findBox")
    public List<OrderBean> findBox(String name, int status){
        List<OrderBean> lst = service.findByBox(name,status);
        return getOrderBeans(lst);
    }

    @GetMapping("chaYi/{order}")
    public int chayYi(@PathVariable("order") long orderId){
        return service.chaYi(orderId);
    }

    @GetMapping("jieSuan/{orderId}/{num}/{price}")
    public void jieSuan(@PathVariable("orderId") long orderId,@PathVariable("num") int num,@PathVariable("price")float price){
        service.jieSuan(orderId,num,price);
    }


    /**
     * 转换状态
     */
    private List<OrderBean> getOrderBeans(List<OrderBean> lst) {
        for (OrderBean o:lst){
            if (o.getStatus() ==0){
                o.setNewStatus("供货中");
            }else if(o.getStatus() ==1){
                o.setNewStatus("已完成");
            }else if (o.getStatus() ==2){
                o.setNewStatus("未供货");
            }
            else {
                o.setNewStatus("未完成");
            }
        }

        return lst;
    }




}
